package controllers

import (
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/orm"
	"hello/models"
)

type RegController struct {
	beego.Controller
}

func (this * RegController)ShowReg()  {
	this.TplName="register.html"
}

/**
处理浏览器注册传递的数据
 */
func (this * RegController)HandleReg()  {
	name := this.GetString("userName")
	passwd := this.GetString("password")
	//beego.Info(name,passwd)  打印日志

	if name==""||passwd=="" {
		beego.Info("用户名或密码不能为空")
		this.TplName="register.html"
		return
	}
	o := orm.NewOrm()
	user:=models.User{}

	user.UserName=name
	user.Passwd=passwd

	_,err:=o.Insert(&user)
	if err!=nil {
		beego.Info("插入数据失败")
		return
	}

	//转发(渲染)：路由地址不变
	this.TplName="login.html"
	//重定向：显示新地址,浏览器进行两次请求，而且不能传递数据
	this.Redirect("/",302)
	//this.Ctx.WriteString("注册成功")
}

type LoginController struct {
	beego.Controller
}

func (this * LoginController)ShowLogin()  {
	this.TplName="login.html"
}
func (this * LoginController)HandleLogin()  {
	name := this.GetString("userName")
	passwd := this.GetString("password")
	if name==""||passwd==""  {
		beego.Info("用户名或密码不能为空")
		this.TplName="login.html"
		return
	}
	//beego.Info(name,passwd)
	o:=orm.NewOrm()
	user:=models.User{}
	user.UserName=name
	//read一次只查询一个
	err:=o.Read(&user,"UserName","Passwd")
	if err!=nil {
		beego.Info("查询失败")
		this.TplName="login.html"
		return
	}

	if user.Passwd!=passwd {
		this.TplName="login.html"
		return
	}
	this.Ctx.WriteString("登录成功")

}